<template>
  <FIModel
    title="新增代理任务"
    width="860"
    v-model="showModel"
    @close="closeClick"
    :confirmLoading="saveLoading"
    @confirm="saveFunc(ruleFormRef)"
  >
    <FIForm ref="ruleFormRef " :model="ruleForm" :rules="rules" label-width="100px" :size="formSize">
      <el-row :span="24">
        <el-col :span="wrapperSpan">
          <el-form-item label="开始时间" prop="delegateStartDate">
            <!-- <FIDatePicker v-model="ruleForm.delegateStartDate" type="date" placeholder="请输入" /> -->
            <FIDatePicker
              v-model="ruleForm.delegateStartDate"
              value-format="YYYYMMDD"
              placeholder="请选择"
              :disabled-date="(date) => checkDateDisabled(date, ruleForm.delegateEndDate)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan">
          <el-form-item label="结束时间" prop="delegateEndDate">
            <!-- <FIDatePicker v-model="ruleForm.delegateEndDate" type="date" placeholder="请输入" /> -->
            <FIDatePicker
              v-model="ruleForm.delegateEndDate"
              value-format="YYYYMMDD"
              placeholder="请选择"
              :disabled-date="(date) => checkDateDisabled(ruleForm.delegateStartDate, date)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan">
          <el-form-item label="委托人" prop="delegater">
            <!-- <FIAutoInput
              v-model="ruleForm.delegaterName"
              :options="delegaterList"
              value-key="userCName"
              :displayKey="['loginName', 'userCName']"
              placeholder="请输入"
              clearable
              @select="
                (item) => {
                  ruleForm.delegater = item.loginName
                }
              "
            > -->
            <FISelect
              v-model="ruleForm.delegater"
              :options="delegaterList"
              valueCustom="userId"
              :props="{ value: 'userId', label: 'userName' }"
              :displayKey="['userId', 'userName']"
              placeholder="请输入"
              filterable
              @select="
                (item) => {
                  ruleForm.delegaterName = item.userName
                }
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan">
          <el-form-item label="受理人" prop="accepter">
            <!-- <FIAutoInput
              v-model="ruleForm.accepterName"
              :options="delegaterList"
              value-key="userCName"
              :displayKey="['loginName', 'userCName']"
              placeholder="请输入"
              clearable
              @select="
                (item) => {
                  ruleForm.accepter = item.loginName
                }
              "
            > -->
            <FISelect
              v-model="ruleForm.accepter"
              :options="accepterList"
              valueCustom="userId"
              :props="{ value: 'userId', label: 'userName' }"
              :displayKey="['userId', 'userName']"
              placeholder="请输入"
              filterable
              @select="
                (item) => {
                  ruleForm.accepterName = item.userName
                }
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="代理说明" prop="remark">
            <FIInput v-model="ruleForm.remark" type="textarea" rows="3"></FIInput>
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan">
          <el-form-item name="delegateType" label="委托类型">
            <FISelect
              v-model="ruleForm.delegateType"
              valueCustom="value"
              :options="[
                { value: 'USER', label: '按用户' },
                { value: 'ROLE', label: '按角色' },
                { value: 'DEPT', label: '按部门' },
              ]"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan"></el-col>
        <el-col v-if="ruleForm.delegateType == 'ROLE'" :span="wrapperSpan">
          <el-form-item name="delegateRole" label="委托人角色">
            <FISelect
              v-model="ruleForm.delegateRole"
              :props="{ value: 'roleId', label: 'roleName' }"
              :options="delegateRoleList"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="ruleForm.delegateType == 'ROLE'" :span="wrapperSpan">
          <el-form-item name="acceptRole" label="受理人角色">
            <FISelect
              v-model="ruleForm.acceptRole"
              :props="{ value: 'roleId', label: 'roleName' }"
              :options="accepterRoleList"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="ruleForm.delegateType == 'DEPT'" :span="wrapperSpan">
          <el-form-item name="delegateDept" label="委托人部门">
            <FISelect
              v-model="ruleForm.delegateDept"
              :props="{ value: 'deptId', label: 'deptName' }"
              :options="delegateDeptList"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="ruleForm.delegateType == 'DEPT'" :span="wrapperSpan">
          <el-form-item name="acceptDept" label="受理人部门">
            <FISelect
              v-model="ruleForm.acceptDept"
              :props="{ value: 'deptId', label: 'deptName' }"
              :options="accepterDeptList"
            />
          </el-form-item>
        </el-col>

        <el-col :span="wrapperSpan">
          <el-form-item name="delegateScopeType" label="代理范围">
            <FISelect
              v-model="ruleForm.delegateScopeType"
              valueCustom="value"
              :options="[
                { value: 'ALL', label: '全部代理' },
                { value: 'PROCESS', label: '流程代理' },
                { value: 'NODE', label: '活动代理' },
              ]"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="wrapperSpan"></el-col>
        <el-col
          v-if="ruleForm.delegateScopeType == 'PROCESS' || ruleForm.delegateScopeType == 'NODE'"
          :span="wrapperSpan"
        >
          <el-form-item name="processDefCode" label="流程定义">
            <FISelect
              v-model="ruleForm.processDefCode"
              :props="{ value: 'processKey', label: 'processName' }"
              :options="processDefCodeList"
              :display-key="['processName']"
              filterable
              :multiple="ruleForm.delegateScopeType != 'NODE'"
              @change="
                (val) => {
                  console.log('-----====----000----', val)
                }
              "
            />
            <!-- <FIAutoInput
              v-model="ruleForm.processDefName"
              :options="processNodeCodeList"
              value-key="processDefName"
              :displayKey="['processDefCode', 'processDefName']"
              @select="
                (item) => {
                  ruleForm.processDefCode = item.processDefCode
                }
              "
            >
              <template #default="{ item }">
                <div>{{ item.nodeKey }} {{ item.nodeName }}</div>
              </template>
            </FIAutoInput> -->
          </el-form-item>
        </el-col>
        <el-col v-if="ruleForm.delegateScopeType == 'NODE'" :span="wrapperSpan">
          <el-form-item name="processNodeCode" label="流程节点">
            <!-- <FISelect
              v-model="ruleForm.processNodeCode"
              :props="{ value: 'nodeKey', label: 'nodeName' }"
              :options="processNodeCodeList"
            /> -->
            <FIAutoInput
              v-model="ruleForm.nodeName"
              :options="processNodeCodeList"
              value-key="nodeName"
              :displayKey="['nodeKey', 'nodeName']"
              :disabled="!ruleForm.processDefCode"
              @select="
                (item) => {
                  ruleForm.processNodeCode = item.nodeKey
                }
              "
            >
              <template #default="{ item }">
                <div>{{ item.nodeKey }} {{ item.nodeName }}</div>
              </template>
            </FIAutoInput>
          </el-form-item>
        </el-col>
      </el-row>
    </FIForm>
  </FIModel>
</template>
<script setup lang="ts">
import FIModel from '@/components/FIModel.vue'
import FIAutoInput from '@/components/FIAutoInput.vue'
import { onMounted, reactive, ref, watch } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { apiRequestPost } from '@/api/globalApi.js'
import { apiQueryDelegate, apiQueryAllProcesses } from '@/api/modules/EWPT.js'
import { apiQueryProcessNode } from '@/api/modules/EW.js'
import { checkDateDisabled } from '@/utils/common'
import { useMessage } from '@/hooks/message'
import FIDatePicker from '@/components/FIDatePicker.vue'
import FISelect from '@/components/FISelect/index.vue'
import moment from 'moment'
const props = defineProps({
  type: {
    type: String,
    default: '',
  },
  visible: {
    type: Boolean,
    default: false,
  },
  delegaterList: {
    type: Array,
    default: () => [],
  },
  accepterList: {
    type: Array,
    default: () => [],
  },
})
const wrapperSpan = 12
const emits = defineEmits(['close', 'update:visible', 'confirm', 'save-ok'])
const showModel = ref(props.visible)
watch(
  () => props.visible,
  (val) => {
    if (showModel.value !== val) {
      showModel.value = val
    }
  }
)

watch(
  () => showModel.value,
  (val) => {
    ruleForm.delegateStartDate = ''
    ruleForm.delegateEndDate = ''
    ruleForm.delegater = ''
    ruleForm.delegaterName = ''
    ruleForm.delegateRole = ''
    ruleForm.delegateDept = ''
    ruleForm.accepter = ''
    ruleForm.accepterName = ''
    ruleForm.acceptRole = ''
    ruleForm.acceptDept = ''
    ruleForm.remark = ''
    ruleForm.delegateType = ''
    ruleForm.delegateScopeType = ''
    ruleForm.processDefCode = '' // 流程定义
    ruleForm.processDefName = '' // 流程定义名称
    ruleForm.processNodeCode = '' // 流程节点
    // 只有值改变时才触发更新，避免无限循环
    if (val !== props.visible) {
      emits('update:visible', val)
    }
  }
)
interface RuleForm {
  delegateStartDate: string
  delegateEndDate: string
  delegater: string
  delegaterName: string
  delegateRole: string
  delegateDept: string
  accepter: string
  accepterName: string
  acceptRole: string
  acceptDept: string
  remark: string
  delegateType: string
  delegateScopeType: string
  processDefCode: string | string[] // 流程定义
  processDefName: string
  processNodeCode: string // 流程节点
  nodeName: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<RuleForm>({
  delegateStartDate: '', // 代理开始时间
  delegateEndDate: '', // 代理结束时间
  delegater: '', // 委托人
  delegaterName: '', // 委托人名称
  delegateRole: '', // 委托人角色
  delegateDept: '', // 委托人部门
  accepter: '', // 受理人
  accepterName: '', // 受理人名称
  acceptRole: '', // 受理人角色
  acceptDept: '', // 受理人部门
  remark: '', // 代理说明
  delegateType: '', // 代理类型
  delegateScopeType: '', // 代理范围
  processDefCode: '', // 流程定义
  processDefName: '', // 流程定义名称
  processNodeCode: '', // 流程节点
  nodeName: '', // 流程节点名称
})
const rules = reactive<FormRules<RuleForm>>({
  delegateStartDate: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  delegateEndDate: [{ required: false, message: '请选择结束时间', trigger: 'blur' }],
  delegater: [{ required: true, message: '请选择委托人', trigger: 'blur' }],
  accepter: [{ required: true, message: '请选择受理人', trigger: 'blur' }],
  remark: [
    {
      required: false,
      message: '请输入代理说明',
      trigger: 'blur',
    },
  ],
  delegateType: [
    {
      required: false,
      message: '请输入描述',
      trigger: 'blur',
    },
  ],
  delegateScopeType: [
    {
      required: false,
      message: '请输入代理范围',
      trigger: 'blur',
    },
  ],
})
watch(
  () => ruleForm.delegateScopeType,
  (val, oldVal) => {
    if (val != oldVal) {
      processNodeCodeList.value = []
      ruleForm.processDefCode = ''
      ruleForm.processDefName = ''
      ruleForm.nodeName = ''
      ruleForm.processNodeCode = ''
    }
    // if (val == 'ALL') {
    //   processNodeCodeList.value = []
    //   ruleForm.processDefCode = ''
    //   ruleForm.processDefName = ''
    //   ruleForm.nodeName = ''
    //   ruleForm.processNodeCode = ''
    // } else if (val == 'PROCESS') {
    //   ruleForm.processDefCode = []
    //   ruleForm.processDefName = ''
    //   ruleForm.nodeName = ''
    //   ruleForm.processNodeCode = ''
    // } else if (val == 'NODE') {
    //   processNodeCodeList.value = []
    //   ruleForm.processDefCode = ''
    //   ruleForm.nodeName = ''
    // }
  }
)
watch(
  () => ruleForm.processDefCode,
  (val, oldVal) => {
    if (val && ruleForm.delegateScopeType == 'NODE') {
      if (val != oldVal) {
        processNodeCodeList.value = []
        ruleForm.nodeName = ''
        ruleForm.processNodeCode = ''
      }
      const obj = {
        processKey: ruleForm.processDefCode,
        current: 1,
        size: 9999,
      }
      getProcessNodeCode(obj)
    }
  }
)
const closeClick = () => {
  emits('update:visible', false)
  emits('close')
}
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log('submit!0001', formEl, ruleFormRef.value)
  console.log('submit!', formEl, ruleFormRef.value)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const saveLoading = ref(false)
const saveFunc = async (formEl: FormInstance | undefined) => {
  if (!ruleForm.delegateStartDate) {
    useMessage().error('请选择开始时间')
    return
  }
  if (!ruleForm.delegater) {
    useMessage().error('请选择委托人')
    return
  }
  if (!ruleForm.accepter) {
    useMessage().error('请选择受理人')
    return
  }
  if (ruleForm.delegater == ruleForm.accepter) {
    useMessage().error('受理人不能和委托人相同')
    return
  }
  //   ruleForm.delegateStartDate = ruleForm.delegateStartDate.toISOString()
  //   ruleForm.delegateEndDate = ruleForm.delegateEndDate.toISOString()
  //   ruleForm.delegateStartDate = ruleForm.delegateStartDate.substring(0, 10)
  //   ruleForm.delegateEndDate = ruleForm.delegateEndDate.substring(0, 10)
  // ruleForm.delegateStartDate = Date.parse(ruleForm.delegateStartDate)
  // ruleForm.delegateEndDate = Date.parse(ruleForm.delegateEndDate)
  ruleForm.delegateStartDate = moment(ruleForm.delegateStartDate).format('yyyyMMDD')
  ruleForm.delegateEndDate = moment(ruleForm.delegateEndDate).format('yyyyMMDD')
  if (ruleForm.delegateEndDate && ruleForm.delegateEndDate < ruleForm.delegateStartDate) {
    useMessage().error('结束时间不能小于开始时间')
    return
  }
  const tempObj = {
    ...ruleForm,
  }
  if (Array.isArray(tempObj.processDefCode) && tempObj.processDefCode.length > 0) {
    tempObj.processDefCode = tempObj.processDefCode.join(',')
  }
  saveLoading.value = true
  apiRequestPost('/bpm-service/TaskDelegate/saveDelegate', tempObj)
    .then((res) => {
      saveLoading.value = false
      if (res.data.success) {
        emits('save-ok', res.data)
        useMessage().success('新增成功')
        closeClick()
      }
    })
    .catch(() => {
      saveLoading.value = false
    })
}

const delegateRoleList = ref([])
const delegateDeptList = ref([])
const accepterRoleList = ref([])
const accepterDeptList = ref([])

watch(
  () => ruleForm.delegateType,
  (val, oldVal) => {
    if (val != oldVal) {
      ruleForm.delegateRole = ''
      ruleForm.delegateDept = ''
      ruleForm.acceptRole = ''
      ruleForm.acceptDept = ''
    }
  },
  {
    deep: true,
    immediate: true,
  }
)
watch(
  () => ruleForm.delegaterName,
  (val, oldVal) => {
    console.log('ruleForm.delegaterName----', val, oldVal)
    if (val != oldVal) {
      ruleForm.delegateRole = ''
      ruleForm.delegateDept = ''
    }
    if (val) {
      delegateDeptList.value = []
      delegateRoleList.value = []
      // 获取角色信息，部门信息
      getRoleAddDeptList(ruleForm.delegater, 'delegate')
    }
  },
  {
    deep: true,
    immediate: true,
  }
)
watch(
  () => ruleForm.accepterName,
  (val, oldVal) => {
    console.log('ruleForm.delegater', val, oldVal)
    if (val != oldVal) {
      ruleForm.acceptDept = ''
      ruleForm.acceptRole = ''
    }
    if (val) {
      accepterDeptList.value = []
      accepterRoleList.value = []
      // 获取角色信息，部门信息
      getRoleAddDeptList(ruleForm.accepter, 'accepter')
    }
  },
  {
    deep: true,
    immediate: true,
  }
)
const getRoleAddDeptList = (val, type) => {
  let params = {
    userId: val,
  }
  apiQueryDelegate(params).then((res) => {
    if (res.data.success) {
      res.data.data.forEach((item: any) => {
        if (item?.roleId) {
          if (type == 'delegate') {
            delegateRoleList.value.push(item)
          } else {
            accepterRoleList.value.push(item)
          }
        } else {
          if (type == 'delegate') {
            delegateDeptList.value.push(item)
          } else {
            accepterDeptList.value.push(item)
          }
        }
      })
    }
  })
}
// 所有流程
const processDefCodeList = ref([])
// 查询所有流程
const getAllProcesses = () => {
  apiQueryAllProcesses().then((res) => {
    if (res.data.success === true) {
      processDefCodeList.value = res.data.data || []
    }
  })
}
// 流程节点
const processNodeCodeList = ref([])
const getProcessNodeCode = (obj) => {
  apiQueryProcessNode(obj).then((res) => {
    if (res.data.success) {
      processNodeCodeList.value = res.data.data.result
    }
  })
}
onMounted(() => {
  getAllProcesses()
})
</script>
